﻿#include "tabitem.h"
#include "ui_tabitem.h"

TabItem::TabItem(QWidget *parent, ResType::TYPE type) :
    BaseEditor(parent),_type(type),
    ui(new Ui::TabItem)
{
    ui->setupUi(this);

    switch (_type) {
    case ResType::Anime:
        table=TD_RES_ANIME;
        break;
    case ResType::Comic:
        table=TD_RES_COMIC;
        break;
    case ResType::Game:
        table=TD_RES_GAME;
        break;
    case ResType::Novel:
        table=TD_RES_NOVEL;
        break;
    case ResType::Picture:
        table=TD_RES_PICTURE;
        break;
    case ResType::Music:
        table=TD_RES_MUSIC;
        break;
    case ResType::Video:
        table=TD_RES_VIDEO;
        break;
    case ResType::Software:
        table=TD_RES_SOFTWARE;
        break;
    case ResType::URL:
        table=TD_RES_URL;
        break;
    case ResType::Location:
        table=TD_RES_LOCATION;
        break;
    case ResType::Pool:
        table=TD_RES_POOL;
        break;
    }
    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);

    updateView();
    createMenu();
}

TabItem::~TabItem()
{
    delete ui;
}

void TabItem::updateView()
{
    model->setTable(table);
    model->select();
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("名称"));    //label
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("标签"));    //tag
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("评级"));    //rate
    ui->tableView->hideColumn(4);   //detail
    ui->tableView->hideColumn(5);   //addition
    ui->tableView->resizeColumnToContents(1);
    ui->tableView->resizeColumnToContents(2);
}

void TabItem::newItem()
{
    ItemAdd item(this,table);
    if(item.exec() == QDialog::Accepted)
        updateView();
}

void TabItem::removeItem()
{
    if(ui->tableView->currentIndex().isValid())
    {
        int curRow = ui->tableView->currentIndex().row();
        model->removeRow(curRow);
    }
}

void TabItem::edit_on()
{
    isEdit=true;
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);
    updateMenu();
}

void TabItem::edit_off()
{
    isEdit=false;
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);
    updateMenu();
}

void TabItem::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString detail=model->data(index.sibling(index.row(),4)).toString();
        ui->detail->setPlainText(detail);
        QString addition=model->data(index.sibling(index.row(),5)).toString();
        ui->addition->setText(addition);
    }
}
